//
//  MinePurchaseRecordViewController.swift
//  MT
//
//  Created by M on 2019/12/31.
//  Copyright © 2019 张强. All rights reserved.
//

import UIKit
/// 网络、通用
import MTCategory

import Moya
import Result
import RxSwift
import RxCocoa
/// 其它
import YPNavigationBarTransition
import MJRefresh

class MinePurchaseRecordViewController: BaseViewController {

    var models: [MinePurchaseRecordModel]? {
        didSet {
            tableView.reloadData()
        }
    }
    
    /// MTProvider
    private lazy var provider: MTProvider<PurchaseApi> = {
        return MTProvider<PurchaseApi>(plugins: [])
    }()
    private let disposeBag = DisposeBag()
    
    var curPage: Int = 0
    
    lazy var tableView: UITableView = {
        let tv = UITableView(frame: self.view.bounds, style: .grouped)
        tv.delegate = self
        tv.dataSource = self
        tv.backgroundColor = UIColor(hex: 0x161616)
        tv.mj_footer = ViewFactory.normalFooter(target: self, selector: #selector(loadMoreData))
            //MJRefreshAutoNormalFooter(refreshingTarget: self, refreshingAction: #selector(loadMoreData))
        tv.register(MinePurchaseRecordTableViewCell.self, forCellReuseIdentifier: String(describing: MinePurchaseRecordTableViewCell.self))
        tv.emptySetView = ViewFactory.emptySetView { [weak self] in

            guard let weakSelf = self else { return }

            weakSelf.loadDatas()

        }
        return tv
    }()
}

// MARK: ------------------------------------ Overrides ----------------------------------------
extension MinePurchaseRecordViewController {
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setup()
        initializeUI()
        loadDatas()
    }
    
}


// MARK: ---------------------------------------- 初始化 --------------------------------------------
extension MinePurchaseRecordViewController {
    
    private func setup() {
        navigationItem.title = "全部记录"
        /// 设置回退按钮
        let button = UIButton(frame: CGRect(x: 0, y: 0, width: 30, height: 30))
        button.setImage(UIImage(named: "nav_back"), for: .normal)
        button.adjustsImageWhenHighlighted = false
        button.addTarget(self, action: #selector(purchseRecordViewController(didClickPopButton:)), for: .touchUpInside)
        let leftButton = UIBarButtonItem(customView: button)
        self.navigationItem.leftBarButtonItem = leftButton
    }
    
    private func initializeUI() {
        view.addSubview(tableView)
        tableView.snp.makeConstraints { (make) in
            make.edges.equalTo(view)
        }
    }
    
}


// MARK: ---------------------------------------- 事件方法 --------------------------------------------
@objc
extension MinePurchaseRecordViewController {
    
    private func purchseRecordViewController(didClickPopButton sender: UIButton) {
        self.navigationController?.popViewController(animated: true)
    }
    
    private func loadMoreData() {
        loadDatas(isAppending: true)
    }
    
}

// MARK: ------------------------------------ 数据请求 ----------------------------------------
extension MinePurchaseRecordViewController {
    
    private func loadDatas(isAppending: Bool = false) {
        let params: [String: Any] = ["curPage": curPage,
                                     "pageSize": 10]

        provider.rx.requestResult(.queryDetail(params)).subscribe(onNext: { [weak self] (result: Result<MinePurchaseRecordResponseModel, AnyError>, isCache: Bool) in
            guard let weakself = self else { return }
            weakself.tableView.mj_footer?.endRefreshing()
            switch result {

            case let .success(response):
                if let code = response.code, code == 200, let result = response.result {
                    weakself.curPage += 1
                    DispatchQueue.main.async {
                        if !isAppending {
                            weakself.models = result
                        } else if weakself.models != nil {
                            weakself.models! += result
                        }
                    }
                }
                break
                
            case .failure(_):
                break
            }
            
        }).disposed(by: disposeBag)
    }
    
}

// MARK: ------------------------------------ 所有代理 ----------------------------------------
// MARK: ------------------------------------ UITableViewDelegate ----------------------------------------
extension MinePurchaseRecordViewController: UITableViewDelegate {
    
}

// MARK: ------------------------------------ UITableViewDataSource ----------------------------------------
extension MinePurchaseRecordViewController: UITableViewDataSource {
 
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        models?.count ?? 0
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        88
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let model = models?[indexPath.row]
        guard let c = tableView.dequeueReusableCell(withIdentifier: String(describing: MinePurchaseRecordTableViewCell.self), for: indexPath) as? MinePurchaseRecordTableViewCell else {
            return tableView.dequeueReusableCell(withIdentifier: String(describing: MinePurchaseRecordTableViewCell.self), for: indexPath)
        }
        c.model = model
        return c
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        CGFloat.leastNonzeroMagnitude
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        CGFloat.leastNonzeroMagnitude
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        nil
    }
    
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        nil
    }
    
}
